package com.woniuxy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.woniuxy.bean.DataGridView;
import com.woniuxy.bean.RoleVo;
import com.woniuxy.mapper.RoleMapper;
import com.woniuxy.pojo.Role;
import com.woniuxy.pojo.User;
import com.woniuxy.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public DataGridView<RoleVo> findRolesByUid(int uid) {
        DataGridView<RoleVo> dataGridView=new DataGridView<>();
        //查询出所有的角色
        List<Role> roles=this.roleMapper.selectAllRoles();
        //通过用户id查询出该用户所拥有的角色集合
        List<Role> rolesbyUser=this.roleMapper.selectRolesByUid(uid);
        List<RoleVo> roleVos=new ArrayList<RoleVo>();
        for(Role role:roles){
            RoleVo roleVo=new RoleVo();
            roleVo.setId(role.getId());
            roleVo.setRolename(role.getRolename());
            for(Role roleItem:rolesbyUser){
                if(role.getId()==roleItem.getId()){
                    roleVo.LAY_CHECKED=true;
                }
            }
            roleVos.add(roleVo);
        }
        dataGridView.setData(roleVos);
        return dataGridView;
    }
    @Override
    public DataGridView<Role> findRolesByPage(RoleVo roleVo) {
        DataGridView<Role> dataGridView=new DataGridView<Role>();
        //必须要使用Page对象进行接收
        Page page= PageHelper.startPage(roleVo.getPage(),roleVo.getLimit());
        List<Role> roleList=this.roleMapper.selectRolesByRole(roleVo);
        //然后在将page对象中getTotal()获取的值再复制为DataGridView中count
        dataGridView.setCount(page.getTotal());
        dataGridView.setData(roleList);
        return dataGridView;
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void assignRight(Integer rid, Integer[] perids) {
        this.roleMapper.deleteRolePermission(rid);
        if(perids!=null&&perids.length>0){
            for(Integer perid:perids){
                this.roleMapper.insertRolePermission(rid,perid);
            }
        }
    }
}
